<template>
  <div class="login-box">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>卡片名称</span>
      </div>
      <el-form
        status-icon
        ref="logonForm"
        label-width="100px"
        class="demo-ruleForm"
        :model="loginForm"
      >
        <el-form-item
          label="用户名"
          prop="username"
          :rules="[
            { require: true, message: '用户名不能为空', trigger: 'blur' },
            { min: 6, max: 12, message: '长度在6-12位字符', trigger: 'blur' },
          ]"
        >
          <el-input v-model="loginForm.username"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          :rules="[
            { require: true, message: '密码不能为空', trigger: 'blur' },
            { min: 6, max: 12, message: '长度在6-12位字符', trigger: 'blur' },
          ]"
        >
          <el-input type="password" v-model="loginForm.password"></el-input>
        </el-form-item>
        <el-form-item class="submit-btn">
          <el-button type="primary" @click="submitForm('logonForm')"
            >提交</el-button
          >
          <el-button @click="resetForm('logonForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loginForm: {
        username: "",
        password: "",
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (
          valid &&
          this.loginForm.username != "" &&
          this.loginForm.password != ""
        ) {
          this.axios
            .post(
              "https://rapserver.sunmi.com/app/mock/340/login",
              this.loginForm
            )
            .then(({ data }) => {
              if (data.status === 200) {
                localStorage.setItem("username", data.username);
                localStorage.setItem("token", data.token);
                this.$message({ message: data.message, type: "success" });
                this.$router.push("/home");
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          localStorage.removeItem("token");
          this.$message({
            message: "请正确输入",
            type: "error",
            duration: "1000",
          });
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style lang="scss">
.login-box {
  width: 100%;
  height: 100%;
  position: absolute;
  background-color: #409eff;
  .el-card__header {
    font-size: 24px;
  }
  .box-card {
    width: 450px;
    margin: 200px auto;
  }
}
</style>
